<template>
  <el-dialog :title="dialogTitle" v-model="dialogVisible" fullscreen>
    <el-form size="large" ref="formRef" :model="formData" :rules="formRules" label-width="100px"
      v-loading="formLoading">
      <el-row :gutter="20">
        <!-- <el-col :span="8">
          <el-form-item label="设备id" prop="equipmentId">
            <el-input v-model="formData.equipmentId" placeholder="请输入设备id" />
          </el-form-item>
        </el-col> -->

        <el-col :span="8">
          <el-form-item label="点检人" prop="checkUser">
            <el-select clearable filterable v-model="formData.checkUser" placeholder="请选择">
              <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="点检时间" prop="checkTime">
            <el-date-picker v-model="formData.checkTime" type="date" value-format="x" placeholder="选择点检时间" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="点检结果" prop="checkResult">
            <el-radio-group v-model="formData.checkResult">
              <el-radio disabled v-for="dict in getStrDictOptions(DICT_TYPE.CHECK_PASS)" :key="dict.value"
                :label="dict.value">
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <!-- <el-col :span="8">
          <el-form-item label="点检通过项ID" prop="checkResult">
            <el-input v-model="formData.checkItemId" placeholder="" />
          </el-form-item>
        </el-col> -->


        <el-col :span="16">
          <el-form-item label="点检说明" prop="remark">
            <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" v-model="formData.remark" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 列表 -->
      <el-row :gutter="24">
        <el-col :span="24">
          <ContentWrap>
            <el-table border :row-key="row => row.id" ref="tableRef" v-loading="loading" :data="list" :stripe="true"
              :show-overflow-tooltip="true" @selection-change="handleRowCheckboxChange">
              <el-table-column type="selection" width="55" />
              <el-table-column label="点检项名称" align="center" prop="name" width="150" />
              <el-table-column label="描述" align="center" prop="description" width="400">
                <template #default="scope">
                  <div class="rich-text-content" v-html="scope.row.description"></div>
                </template>
              </el-table-column>

              <!-- 备注列：每行显示一个输入框 -->
              <el-table-column label="备注" width="320px">
                <template #default="scope">
                  <el-input v-model="scope.row.remark" placeholder="请输入备注" />
                </template>
              </el-table-column>

              <!-- 备注列：每行显示一个输入框 -->
              <el-table-column label="附件" min-width="320px">
                <template #default="scope">
                  <UploadFile :isShowTip="false" v-model="scope.row.files" />
                </template>
              </el-table-column>

            </el-table>
            <!-- 分页 -->
          </ContentWrap>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">提 交</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { EquipmentCheckRecordApi, EquipmentCheckRecord } from '@/api/business/equipmentcheckrecord'
import * as UserApi from '@/api/system/user'
import { EquipmentCheckTypeApi, EquipmentCheckType } from '@/api/business/equipmentchecktype'
import { EquipmentCheckConfigApi, EquipmentCheckConfig } from '@/api/business/equipmentcheckconfig'


import {
  getUserProfile,
} from '@/api/system/user/profile'

/** 点检记录 表单 */
defineOptions({ name: 'EquipmentCheckRecordForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  equipmentId: undefined,
  checkUser: undefined,
  checkTime: undefined,
  checkResult: undefined,
  checkItemId: [],
  remark: undefined,
  detailDO: []
  // detailDO: {
  //   checkItemId: undefined,
  //   files: [],
  //   fileName: undefined,
  //   remark: undefined
  // }
})
const formRules = reactive({
  equipmentId: [{ required: true, message: '设备id不能为空', trigger: 'blur' }],
  checkUser: [{ required: true, message: '点检人不能为空', trigger: 'blur' }],
  checkTime: [{ required: true, message: '点检时间不能为空', trigger: 'blur' }]

})
const formRef = ref() // 表单 Ref

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const tableRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {


  resetForm()

  //设置默认点检日期
  formData.value.checkTime = new Date().getTime() //设置当前时间戳

  console.log("设备ID", id);

  formData.value.equipmentId = id

  checkedIds.value = []
  allCheckedIds.value = []


  dialogTitle.value = t('action.' + type)
  formType.value = type


  //默认设置当前用户为点检人
  const res = await getUserProfile()
  formData.value.checkUser = res.id
  console.log("当前用户", formData.value.checkUser);
  dialogVisible.value = true
  //查询点检项
  try {
    const params = {
      targetId: id,
      type: 2//按设备
    }

    const res = await EquipmentCheckTypeApi.checkTypeMapList(params)
    allCheckedIds.value = res.bind.map(item => item.id)
    checkedIds.value = [...allCheckedIds.value] // 全选

    //必须使用快照 否则选中会有问题
    const finalCheckedIds = [...checkedIds.value]

    console.log("rrrrrr", checkedIds.value, allCheckedIds.value);

    // 替换你原来的 nextTick 部分
    // 在 open 方法中，替换原来的 nextTick 部分
    list.value = res.bind

    nextTick(() => {
      list.value.forEach(row => {
        if (finalCheckedIds) {
          if (finalCheckedIds.includes(row.id)) {
            tableRef.value?.toggleRowSelection(row, true)
          }
        }
      })
    })

    // 可选：触发一次 selectResult 更新表单状态
    selectResult(finalCheckedIds)

    loading.value = false
  } catch (error) {
    loading.value = false
    console.error("获取待绑定数据失败:", error)
  }



  // 修改时，设置数据
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records) => {
  checkedIds.value = records.map((item) => item.id);

  selectResult(checkedIds.value)
}

const selectResult = (selectedIds: number[]) => {
  const isAllSelected = allCheckedIds.value.every(id => selectedIds.includes(id))
  formData.value.checkResult = isAllSelected ? '1' : '2'
}
//用户列表
const userList = ref([])


//全部的
const allCheckedIds = ref([])

const initData = async () => {
  userList.value = await UserApi.getSimpleUserList()
}



/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {

    //组装数据
    formData.value.checkItemId = checkedIds.value || []

    // ✅ 从 list.value 组装 detailDO 数组
    formData.value.detailDO = list.value.map(item => ({
      checkItemId: item.id,        // 必填
      files: item.files || [],     // 可能为空
      remark: item.remark || '',   // 可能为空
      // fileName: 可选，可从文件 URL 提取文件名
    }))

    console.log("提交的数据", formData.value);


    const data = formData.value
    await EquipmentCheckRecordApi.createEquipmentCheckRecord(data)
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    equipmentId: undefined,
    checkUser: undefined,
    checkTime: undefined,
    checkResult: undefined,
    checkItemId: [],
    remark: undefined,
    detailDO: []
  }
  formRef.value?.resetFields()
}


onMounted(() => {
  initData()
})


</script>
